package com.starsray.dynamic.datasource.config;

import com.starsray.dynamic.datasource.constant.RedisKeys;
import com.starsray.dynamic.datasource.listener.DsAddRedisListener;
import com.starsray.dynamic.datasource.listener.DsDeleteRedisListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Configuration
public class RedisListenerConfig {

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter dsAddAdapter, MessageListenerAdapter dsRemoveAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);

        container.addMessageListener(dsAddAdapter, new PatternTopic(RedisKeys.ADD_QUEUE_CHANNEL));
        container.addMessageListener(dsRemoveAdapter, new PatternTopic(RedisKeys.DELETE_QUEUE_CHANNEL));
        return container;
    }

    @Bean
    public MessageListenerAdapter dsAddAdapter(DsAddRedisListener dsAddRedisListener) {
        return new MessageListenerAdapter(dsAddRedisListener, "onMessage");
    }

    @Bean
    public MessageListenerAdapter dsRemoveAdapter(DsDeleteRedisListener dsRemoveRedisListener) {
        return new MessageListenerAdapter(dsRemoveRedisListener, "onMessage");
    }

}
